package com.syxp.pda.action.plan;

import java.io.FileInputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts2.ServletActionContext;

import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import com.syxp.pda.core.command.QueryFilter;
import com.syxp.pda.core.util.TimeFormatUtil;
import com.syxp.pda.core.web.PagingBean;
import com.syxp.pda.core.web.action.BaseAction;
import com.syxp.pda.core.xls.WorkReport;
import com.syxp.pda.entity.base.CHKLine;
import com.syxp.pda.entity.base.CHKPlan;
import com.syxp.pda.entity.base.DefineIDZone;
import com.syxp.pda.entity.base.Duty;
import com.syxp.pda.service.base.DutyService;
import com.syxp.pda.service.plan.CHKPlanService;

public class PlanAction extends BaseAction {
	@Resource
	private CHKPlanService chkplanService;
	@Resource
	private DutyService dutyService;
	
	private int chkPlanID;
	private CHKPlan chkPlan;
	private int start ;
	
	private int limit ;

	public int getStart() {
		return start;
	}

	public void setStart(int start) {
		this.start = start;
	}

	public int getLimit() {
		return limit;
	}

	public void setLimit(int limit) {
		this.limit = limit;
	}

	private int nodeDepth;
	private String nodeId;
	private String importIds;
	private String parNodeId;
	
	private int chkLineID;
	private int zoneID;
	private String dutyDate;
	private int classID;
	private int dutyID;
	
	@Resource
	private WorkReport workReport;
	
	
	public String load() {
		JsonArray jarray=new JsonArray();
		QueryFilter filter = new QueryFilter() ;
		filter.setPagingBean(new PagingBean(start,limit)) ;
		JsonObject result = new JsonObject() ;
		try {
			List<CHKPlan> plans = this.chkplanService.getDao().getAll(filter);
		
			for(CHKPlan o: plans) {
				JsonObject jobj=new JsonObject();
				jobj.addProperty("planName", o.getPlanName());
				jobj.addProperty("chkPlanID", o.getChkPlanID());
				String tid = o.getTeamID();
				if(tid!=null&&!"".equals(tid.trim())) {
					String[] tids = tid.split(",");
					String tnamestr = "";
					for (String id: tids) {System.out.println(this.dutyService+"teamid="+o.getTeamID());
						Duty duty = this.dutyService.loadService(Integer.parseInt(id));
						if(duty!=null){
							tnamestr += "," + duty.getDutyName();
						} else {
							tnamestr += "," + id;
						}
					}
					tnamestr = tnamestr.replaceFirst(",", "");
					jobj.addProperty("teamName", tnamestr);
					jobj.addProperty("teamID", o.getTeamID());
				} else {
					jobj.addProperty("teamName", "");
					jobj.addProperty("teamID", "");
				}
				jobj.addProperty("createDate", TimeFormatUtil.formatDate(o.getCreateDate()));
				jobj.addProperty("operatorCode", o.getOperatorCode());
				jarray.add(jobj);
			}
		} catch(Exception e) {
			e.printStackTrace();
		}
		result.addProperty("totalProperty",chkplanService.getDao().getTotalProperty(filter)) ;
		result.add("result", jarray) ;
		result.addProperty("start", start);
		result.addProperty("limit", limit) ;
		this.jsonString = gson.toJson(result) ;
		System.out.println(jsonString) ;
		return SUCCESS ;
	}
	
	public String save() {
		try {
			this.chkPlan.setCreateDate(new Date());
			this.chkPlan.setOperatorCode("Admin");
			this.chkplanService.addService(this.chkPlan);
			this.jsonString="{success:true}" ;
		} catch(Exception e) {
			e.printStackTrace();
			this.jsonString="{success:false}" ;
		}
		return SUCCESS;
	}
	
	public String delete() {
		try {
			this.chkplanService.removeService(this.chkPlanID);
			this.jsonString="{success:true}" ;
		} catch(Exception e) {
			e.printStackTrace();
			this.jsonString="{success:false}" ;
		}
		return SUCCESS;
	}
	
	public String update() {
		try {
			this.chkplanService.updateService(this.chkPlan);
			this.jsonString="{success:true}" ;
		} catch(Exception e) {
			e.printStackTrace();
			this.jsonString="{success:false}" ;
		}
		return SUCCESS;
	}
	
	public String loadtree() {
		System.out.println(this.nodeDepth+"###"+this.nodeId);
		List list = new ArrayList(); 
		try {
			int id = Integer.parseInt(this.nodeId.split("#")[this.nodeDepth]);
			//int parId = Integer.parseInt(this.parNodeId.split("#")[this.nodeDepth>0?this.nodeDepth-1:0]);
			if(nodeDepth==0) {//点击根节点  获取计划
				List<CHKPlan> plans = this.chkplanService.getDao().getAll();
				for(CHKPlan o: plans) {
					Map map = new HashMap();
					map.put("id", this.nodeId+"#"+o.getChkPlanID());
					map.put("text", o.getPlanName());
					list.add(map);
				}
			} else if(this.nodeDepth==1) {//点击第二层计划节点  获取路线
				List<CHKLine> lines = this.chkplanService.getLines(id);
				for(CHKLine o: lines) {
					Map map = new HashMap();
					map.put("id", this.nodeId+"#"+o.getChkLineID());
					map.put("text", o.getLineName());
					list.add(map);
				}
			} else if(this.nodeDepth==2) {//点击第三层路线节点  获取区域
				List<DefineIDZone> zones = this.chkplanService.getZones(id);
				for(DefineIDZone o: zones) {
					Map map = new HashMap();
					map.put("id", this.nodeId+"#"+o.getZoneID());
					map.put("text", o.getZoneName());
					map.put("leaf", true);
					list.add(map);
				}
			} else if(this.nodeDepth==3) {//点击第四层区域节点  获取该区域下设备巡检计划
//				List<DeviceCheckStandard> deviceCheckStandards = this.chkplanService.get;
//				for(DeviceCheckStandard o: deviceCheckStandards) {
//					Map map = new HashMap();
//					list.add(map);
//				}
			} 
		} catch(Exception e) {
			e.printStackTrace();
		}
		this.jsonString = this.gson.toJson(list);
		System.out.println(this.jsonString);
		return SUCCESS;
	}
	
	public String getUnimportNodes() {
		System.out.println(this.nodeDepth);
		List list = new ArrayList(); 
		try {
			if(this.nodeDepth==1) {//点击第二层计划节点  获取路线
				List<Object[]> lines = this.chkplanService.getUnimportLines();
				for(Object[] o: lines) {
					Map map = new HashMap();
					map.put("id", o[0]);
					map.put("name", o[1]);
					list.add(map);
				}
			} else if(this.nodeDepth==2) {//点击第三层路线节点  获取区域
				List<Object[]> lines = this.chkplanService.getUnimportZones();
				for(Object[] o: lines) {
					Map map = new HashMap();
					map.put("id", o[0]);
					map.put("name", o[1]);
					list.add(map);
				}
			}
		} catch(Exception e) {
			e.printStackTrace();
		}
		this.jsonString = this.gson.toJson(list);
		System.out.println(this.jsonString);
		return SUCCESS;
	}

	public String importNodes() {
		System.out.println(this.nodeDepth+"+"+this.nodeId+"+"+this.importIds);
		if(this.importIds==null||"".equals(this.importIds.trim())) {//没有要导入的节点
			this.jsonString="{success:true}" ;
		} else {
			try {
				List list = new ArrayList();
				String[] idsstr = this.importIds.split(",");
				for(String idstr: idsstr) {
					list.add(Integer.parseInt(idstr));
				}
				
				int id = Integer.parseInt(this.nodeId.split("#")[this.nodeDepth]);
				if(this.nodeDepth==1) {//点击第二层计划节点  导入路线
					this.chkplanService.importLines(id, list);
				} else if(this.nodeDepth==2) {//点击第三层路线节点 导入区域
					this.chkplanService.importZone(id, list);
				}
				this.jsonString="{success:true}" ;
			} catch(Exception e) {
				e.printStackTrace();
				this.jsonString="{success:false}" ;
			}
		}
		System.out.println(this.jsonString);
		return SUCCESS;
	}
	
	public String deleteNode() {
		System.out.println(this.nodeDepth+"+"+this.nodeId+"+"+this.importIds);
		try {
			int id = Integer.parseInt(this.nodeId.split("#")[this.nodeDepth]);
			int parId = Integer.parseInt(this.parNodeId.split("#")[this.nodeDepth-1]);
			if(this.nodeDepth==2) {//点击第二层计划节点  导入路线
				this.chkplanService.removeLine(parId, id);
			} else if(this.nodeDepth==3) {//点击第三层路线节点 导入区域
				this.chkplanService.removeZone(parId, id);
			}
			this.jsonString="{success:true}" ;
		} catch(Exception e) {
			e.printStackTrace();
			this.jsonString="{success:false}" ;
		}
		System.out.println(this.jsonString);
		return SUCCESS;
	}
	
	public String getTaskByZone() {
		List list = new ArrayList(); 
		try {System.out.println(this.chkPlanID+"="+this.chkLineID+"="+this.zoneID+"="+this.dutyDate);
//			this.dutyDate = "2011-10-10";
//			this.chkPlanID = 1;
//			this.chkLineID = 2;
//			this.zoneID = 3;
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
			List list1 = this.chkplanService.getPlanDetail(this.chkPlanID, this.chkLineID, this.zoneID, sdf.parse(this.dutyDate));
			for(Object[] o: (List<Object[]>)list1) {
//				System.out.println("--------------------------------------");
//				for(int i=0; i<o.length; i++) {
//					System.out.println(i+"="+o[i]);
//				}
//				System.out.println("=======================================");
				Map map = new HashMap();
				map.put("DevName", o[8]);
				map.put("CHKItem", o[13]);
				map.put("DutyName", o[18]);
				map.put("ClaName", o[15]);
				map.put("TurnOrder", o[16]);
				map.put("UserName", o[19]);
				map.put("Start_PDA_CHKDateTime", o[20].toString().split(" ")[1]);
				map.put("End_PDA_CHKDateTime", o[21].toString().split(" ")[1]);
				list.add(map);
			}
		} catch(Exception e) {
			e.printStackTrace();
		}
		this.jsonString = this.gson.toJson(list);
		System.out.println(this.jsonString);
		return SUCCESS;
	}
	
	public String queryPlan() {
		System.out.println(this.dutyDate+"="+this.chkLineID+"="+this.dutyID+"="+this.classID);
		List list = new ArrayList(); 
		try {
//			this.dutyDate = "2011-10-10";
//			this.chkPlanID = 1;
//			this.chkLineID = 2;
//			this.zoneID = 3;
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
			List list1 = this.chkplanService.queryPlan(sdf.parse(this.dutyDate), this.chkLineID, this.dutyID, this.classID);//getPlanDetail(this.chkPlanID, this.chkLineID, this.zoneID, sdf.parse(this.dutyDate));
			for(Object[] o: (List<Object[]>)list1) {
//				System.out.println("--------------------------------------");
//				for(int i=0; i<o.length; i++) {
//					System.out.println(i+"="+o[i]);
//				}
//				System.out.println("=======================================");
				Map map = new HashMap();
				map.put("LineName", o[3]);
				map.put("ZoneName", o[6]);
				map.put("DevName", o[8]);
				map.put("CHKItem", o[13]);
				map.put("CHKTypeName", o[12]);
				map.put("CHKPlace", o[10]);
				map.put("Standard", o[12]);
				map.put("DutyName", o[18]);
				map.put("ClaName", o[15]);
				map.put("TurnOrder", o[16]);
				map.put("UserName", o[19]);
				map.put("Start_PDA_CHKDateTime", o[20]);
				map.put("End_PDA_CHKDateTime", o[21]);
				list.add(map);
			}
//			if(this.nodeDepth==2) {//点击第三层路线节点  获取区域
//				List<Object[]> lines = this.chkplanService.getUnimportZones();
//				for(Object[] o: lines) {
//					Map map = new HashMap();
//					map.put("id", o[0]);
//					map.put("name", o[1]);
//					list.add(map);
//				}
//			}
		} catch(Exception e) {
			e.printStackTrace();
		}
		this.jsonString = this.gson.toJson(list);
		System.out.println(this.jsonString);
		return SUCCESS;
	}
	
	/**
	 * 导出Excel文件
	 * @return
	 */
	public String export() {
		List list = new ArrayList(); 
		try {
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
			List list1 = this.chkplanService.queryPlan(sdf.parse(this.dutyDate), this.chkLineID, this.dutyID, this.classID);//getPlanDetail(this.chkPlanID, this.chkLineID, this.zoneID, sdf.parse(this.dutyDate));
			for(Object[] o: (List<Object[]>)list1) {
				String[] plan = new String[13];
				plan[0] = (String)o[3];
				plan[1] = (String)o[6];
				plan[2] = (String)o[8];
				plan[3] = (String)o[13];
				plan[4] = (String)o[12];
				plan[5] = (String)o[10];
				plan[6] = (String)o[12];
				plan[7] = (String)o[18];
				plan[8] = (String)o[15];
				plan[9] = (String)o[16];
				plan[10] = (String)o[19];
				plan[11] = (String)o[20];
				plan[12] = (String)o[21];
				list.add(plan);
			}
			String fname = "计划查询";
			this.workReport.xlsBuilder("PLAN", list);
			HttpServletResponse response = ServletActionContext.getResponse();
			response.setContentType("application/msexcel");// 通知客户文件的mime类型
			response.setHeader("Content-Disposition", "attachment; filename=\"" + new String(fname.getBytes("gb2312"), "ISO8859-1") + ".xls\"");
			String fpath = ServletActionContext.getServletContext().getRealPath("/temp/"+fname);
			OutputStream os = response.getOutputStream();
			InputStream is = new FileInputStream(fpath);
			int readByte = -1;
			while((readByte=is.read())!=-1) {
				os.write(readByte);
			}
			os.flush();
			is.close();
			os.close();
			this.jsonString="{success:true}" ;
		} catch(Exception e) {
			this.jsonString="{success:false}" ;
			e.printStackTrace();
		}
		System.out.println(this.jsonString);
		return null;//SUCCESS;
	}
	
	/**
	 * @return the chkplanService
	 */
	public CHKPlanService getChkplanService() {
		return chkplanService;
	}

	/**
	 * @param chkplanService the chkplanService to set
	 */
	public void setChkplanService(CHKPlanService chkplanService) {
		this.chkplanService = chkplanService;
	}

	/**
	 * @return the chkPlanID
	 */
	public int getChkPlanID() {
		return chkPlanID;
	}

	/**
	 * @param chkPlanID the chkPlanID to set
	 */
	public void setChkPlanID(int chkPlanID) {
		this.chkPlanID = chkPlanID;
	}

	/**
	 * @return the chkPlan
	 */
	public CHKPlan getChkPlan() {
		return chkPlan;
	}

	/**
	 * @param chkPlan the chkPlan to set
	 */
	public void setChkPlan(CHKPlan chkPlan) {
		this.chkPlan = chkPlan;
	}

	/**
	 * @return the dutyService
	 */
	public DutyService getDutyService() {
		return dutyService;
	}

	/**
	 * @param dutyService the dutyService to set
	 */
	public void setDutyService(DutyService dutyService) {
		this.dutyService = dutyService;
	}

	/**
	 * @return the nodeDepth
	 */
	public int getNodeDepth() {
		return nodeDepth;
	}

	/**
	 * @param nodeDepth the nodeDepth to set
	 */
	public void setNodeDepth(int nodeDepth) {
		this.nodeDepth = nodeDepth;
	}

	/**
	 * @return the nodeId
	 */
	public String getNodeId() {
		return nodeId;
	}

	/**
	 * @param nodeId the nodeId to set
	 */
	public void setNodeId(String nodeId) {
		this.nodeId = nodeId;
	}

	/**
	 * @return the importIds
	 */
	public String getImportIds() {
		return importIds;
	}

	/**
	 * @param importIds the importIds to set
	 */
	public void setImportIds(String importIds) {
		this.importIds = importIds;
	}

	/**
	 * @return the parNodeId
	 */
	public String getParNodeId() {
		return parNodeId;
	}

	/**
	 * @param parNodeId the parNodeId to set
	 */
	public void setParNodeId(String parNodeId) {
		this.parNodeId = parNodeId;
	}

	/**
	 * @return the chkLineID
	 */
	public int getChkLineID() {
		return chkLineID;
	}

	/**
	 * @param chkLineID the chkLineID to set
	 */
	public void setChkLineID(int chkLineID) {
		this.chkLineID = chkLineID;
	}

	/**
	 * @return the zoneID
	 */
	public int getZoneID() {
		return zoneID;
	}

	/**
	 * @param zoneID the zoneID to set
	 */
	public void setZoneID(int zoneID) {
		this.zoneID = zoneID;
	}

	/**
	 * @return the dutyDate
	 */
	public String getDutyDate() {
		return dutyDate;
	}

	/**
	 * @param dutyDate the dutyDate to set
	 */
	public void setDutyDate(String dutyDate) {
		this.dutyDate = dutyDate;
	}

	/**
	 * @return the classID
	 */
	public int getClassID() {
		return classID;
	}

	/**
	 * @param classID the classID to set
	 */
	public void setClassID(int classID) {
		this.classID = classID;
	}

	/**
	 * @return the dutyID
	 */
	public int getDutyID() {
		return dutyID;
	}

	/**
	 * @param dutyID the dutyID to set
	 */
	public void setDutyID(int dutyID) {
		this.dutyID = dutyID;
	}

	/**
	 * @return the workReport
	 */
	public WorkReport getWorkReport() {
		return workReport;
	}

	/**
	 * @param workReport the workReport to set
	 */
	public void setWorkReport(WorkReport workReport) {
		this.workReport = workReport;
	}

}
